// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import BaseView from "../base/BaseView";
import StockListComponent from "../base/components/StockListComponent";
import FileModule from "../module/FileModule";
import LogModule from "../module/LogModule";
import MatchModule from "../module/MatchModule";
import SeptkapaModule from "../module/SeptkapaModule";
import TimeModule from "../module/TimeModule";
import DropList from "./items/DropList";
import { ThsRankData } from "./models/ThsRankData";

const {ccclass, property} = cc._decorator;

const SearchConfigKey = 'search_config';

const SelectPlates = 'select_plate';

var DropConfig = [
    {
        key: 'tradeDayCnt',
        data: ['1', '2', '3', '4', '5', '6', '7', '8', '10', '15', '20', '25', '30', '35', '40', '45', '50', '60', '120', '150', '240'],
        value: [1, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 120, 150, 240],
        defaultIndex: 4,
    },
    {   //
        key: 'onlyZhuban',
        data: ['是', '否'],
        value: [false, true],
        defaultIndex: 1,
    },
    {   //
        key: 'upLimitCnt',
        data: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
        value: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        defaultIndex: 0,
    },
    {   //
        key: 'szMin',
        data: ['不限', '10亿', '20亿', '30亿', '40亿', '50亿', '100亿', '200亿', '300亿', '500亿', '1000亿', '2000亿'],
        value: [0, 10, 20, 30, 40, 50, 100, 200, 300, 500, 1000, 2000],
        defaultIndex: 0,
    },
    {   //
        key: 'szMax',
        data: ['不限', '20亿', '30亿', '50亿', '60亿', '80亿', '100亿', '200亿', '300亿', '500亿', '1000亿', '2000亿', '3000亿', '5000亿'],
        value: [100000, 20, 30, 50, 60, 80, 100, 200, 300, 500, 1000, 2000, 3000, 5000],
        defaultIndex: 0,
    },
    {   //
        key: 'hsMin',
        data: ['0%', '1%', '2%', '3%', '5%', '10%', '12%', '15%', '18%','20%', '30%'],
        value: [0, 1, 2, 3, 5, 10, 12, 15, 18, 20, 30],
        defaultIndex: 0,
    },
    {   //
        key: 'hsMax',
        data: ['1%', '2%', '3%', '5%', '10%', '12%', '15%', '18%', '20%', '30%', '不限制'],
        value: [1, 2, 3, 5, 10, 12, 15, 18, 20, 30, 100],
        defaultIndex: 7,
    },
    {   //
        key: 'ownerMin',
        data: ['不限', '1万', '2万', '3万', '5万', '8万', '10万', '20万', '30万', '50万'],
        value: [0, 1, 2, 3, 5, 8, 10, 20, 30, 50],
        defaultIndex: 0,
    },
    {   //
        key: 'ownerMax',
        data: ['不限', '1万', '2万', '3万', '5万', '8万', '10万', '20万', '30万', '50万', '100万'],
        value: [1000, 1, 2, 3, 5, 8, 10, 20, 30, 50, 100],
        defaultIndex: 5,
    },
    {   //
        key: 'volumeMin',
        data: ['不限', '0.1', '0.2', '0.3', '0.35', '0.4', '0.45','0.5', '0.6', '0.65', '0.7', '0.75', '1', '2', '2.5', '3', '4' ,'5', '10'],
        value: [0, 0.1, 0.2, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.65, 0.7, 0.75, 1, 2, 2.5, 3, 4, 5, 10],
        defaultIndex: 4,
    },
    {   //
        key: 'volumeMax',
        data: ['不限', '0.1', '0.2', '0.3', '0.4', '0.5', '1', '2', '2.5', '3', '4', '5', '10'],
        value: [100, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 2, 2.5, 3, 4, 5, 10],
        defaultIndex: 5,
    },
    {   //
        key: 'volumeCount',
        data: ['不限', '全部', '1', '2', '3', '4', '5', '6', '8', '10'],
        value: [0, 9999, 1, 2, 3, 4, 5, 6, 8, 10],
        defaultIndex: 1,
    },
    {   //
        key: 'upFloatMin',
        data: ['不限', '-300%', '-200%', '-100%', '-50%', '-40%', '-30%', '-20%', '-15%','-10%', '-7%', '-5%', '0%', '5%', '7%', '10%', '15%', '20%', '30%', '50%', '100%', '200%', '300%', '400%', '500%'],
        value: [-10000, -300, -200, -100, -50, -40, -30, -20, -15, -10, -7, -5, 0, 5, 7, 10, 15, 20, 30, 50, 100, 200, 300, 400, 500],
        defaultIndex: 0,
    },
    {   //
        key: 'removeLastLimitUp',
        data: ['是', '否'],
        value: [true, false],
        defaultIndex: 1,
    },
    {   //
        key: 'issueDateMin',
        data: ['不限', '1月', '3月', '6月', '1年', '2年', '3年', '5年', '10年'],
        value: [0, 1, 3, 6, 100, 200, 300, 500, 1000],
        defaultIndex: 5,
    },
    {   //
        key: 'issueDateMax',
        data: ['不限', '1月', '3月', '6月', '1年', '2年', '3年', '5年', '10年'],
        value: [10000, 1, 3, 6, 100, 200, 300, 500, 1000],
        defaultIndex: 0,
    },
    {   //
        key: 'removeSt',
        data: ['是', '否'],
        value: [true, false],
        defaultIndex: 0,
    },
	{   //
        key: 'searchInResult',
        data: ['是', '否'],
        value: [true, false],
        defaultIndex: 1,
    },
	{   //
        key: 'upFloatMax',
        data: ['不限', '-10%', '-5%', '0%', '5%', '10%', '20%', '30%', '40%', '50%', '80%', '100%', '200%', '300%', '400%', '500%'],
        value: [10000, -10, -5, 0, 5, 10, 20, 30, 40, 50, 80, 100, 200, 300, 400, 500],
        defaultIndex: 0,
    },
    {   //
        key: 'upLimitType',
        data: ['涨停', '5%', '6%', '7%', '8%', '9%', '10%', '12%', '13', '15%'],
        value: [99, 5, 6, 7, 8, 9, 10, 12, 13, 15],
        defaultIndex: 0,
    },
    {   //
        key: 'otherType',
        data: ['不限', '连续阳线', '持续放量', '持续上涨'],
        value: [0, 1, 2, 3],
        defaultIndex: 0,
    },
];

@ccclass
export default class SearchStockView extends BaseView {

    // LIFE-CYCLE CALLBACKS:
    @property([DropList])
    dropLists: DropList[] = [];

    @property(cc.Prefab)
    stockListPrefab: cc.Prefab = null;

    @property(cc.Node)
    stockListLayer: cc.Node = null;

    stockListComp: StockListComponent = null;

    _searchStocks: any = [];

    onLoad () {
        let lastSearchConfig = SeptkapaModule.getInstance().getValue(SearchConfigKey);

        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            let selectIndex = config.defaultIndex;
            if (lastSearchConfig && lastSearchConfig[config.key] !== undefined) {
                selectIndex = lastSearchConfig[config.key];
            }
            drop.setData(config.data, selectIndex);
        }

        let node = cc.instantiate(this.stockListPrefab);
        this.stockListLayer.addChild(node);
        this.stockListComp = node.getComponent(StockListComponent);
    }

    protected onEnable(): void {
        cc.director.on('SelectStockEvent', this.onSelectStockEvent, this);
    }

    protected onDisable(): void {
        cc.director.off('SelectStockEvent', this.onSelectStockEvent, this);
    }

    onSelectStockEvent (selectIndex) {
        this.createDialog(BaseView.Views.StockInfoView, {stocks: this._searchStocks, selectIndex: selectIndex} );
    }

    onBtnPlate () {
        let selectPlates = SeptkapaModule.getInstance().getValue(SelectPlates);
        if (selectPlates == null) {
            selectPlates = [];
        }
        let params = {
            selects: selectPlates,
            callback: (plates) => {
                this.onSelectPlates(plates);
            },
            isSingle: false,
        };
		this.createDialog(BaseView.Views.SelectPlateView, params);
    }

	onSelectPlates (plates) {
        SeptkapaModule.getInstance().setValue(SelectPlates, plates);
		let stocks = ThsRankData.getInstance().getPlatesStocks(plates);
		this.setStockData(stocks);
	}

    async onBtnSearch () {
        let condition = {};
        let searchConfig = {};
        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            let selectIndex = drop.getSelectIndex();
            condition[config.key] = config.value[selectIndex];
            searchConfig[config.key] = selectIndex;
        }
        SeptkapaModule.getInstance().setValue(SearchConfigKey, searchConfig);
        
		if (condition['searchInResult'] && (this._searchStocks == null || this._searchStocks.length == 0)){
			this.showToast("搜索结果为空，请取消上次搜索结果设置");
		}
		
		let match = new MatchModule();
		let searchStocks = this._searchStocks;
        let stocks = await match.matchStock(condition, searchStocks);
        this.setStockData(stocks);
        this._searchStocks = stocks;
    }

    onBtnSave () {
        if (this._searchStocks.length == 0) {
            this.showToast("列表为空，导出失败");
            return;
        }
        let totalStr = '';
        for (let index = 0; index < this._searchStocks.length; index++) {
            const item = this._searchStocks[index];
            let market = item.market;
            let str = `${item.ts_code}  ${item.name}  市值${Math.ceil(market.total_mv / 10000)}亿  市盈率ttm:${market.pe_ttm}  市净率${market.pb}\n`;
            totalStr += str;
        }

        FileModule.saveStringAsync('search_stock_' + TimeModule.getInstance().strToday(), totalStr, 10);
    }

    //分析板块
    onBtnAnalyse () {
        if (this._searchStocks.length == 0) {
            this.showToast("列表为空");
            return;
        }

        let params = {
            stocks: this._searchStocks,
            type: 'upLimitCount',
        };

        this.createDialog(BaseView.Views.AnalyseStocksView, params);
    }

    onBtnSaveQuick () {
        let searchConfig = {};
        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            let selectIndex = drop.getSelectIndex();
            searchConfig[config.key] = selectIndex;
        }
        let params = {
            type: 'save',
            config: searchConfig,
        };
        this.createDialog(BaseView.Views.SearchConfigView, params);
    }

    onBtnSelectQuick () {
        let params = {
            type: 'select',
            callback: (searchConfig) => {
                this.onQuickSearchConfig(searchConfig);
            },
        };
        this.createDialog(BaseView.Views.SearchConfigView, params);
    }

    onQuickSearchConfig (searchConfig) {
        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            if (searchConfig && searchConfig[config.key] !== undefined) {
                let selectIndex = searchConfig[config.key];
                drop.setSelectIndex(selectIndex);
            }
        }
    }

    setStockData (stocks: any) {
        this.stockListComp.setData(stocks);
        this._searchStocks = stocks;
        LogModule.log('找到股票数量:' + stocks.length);
    }

}
